//
//  GameScene.swift
//  SpriteGame
//
//  Created by teddy on 7/15/16.
//  Copyright (c) 2016 teddy. All rights reserved.
//

import SpriteKit

// 物理模型分类
struct PhysicsCatagory {
    // 我
    static let Teddy : UInt32 = 0x1 << 1
    // 地面
    static let Ground : UInt32 = 0x1 << 2
    // 墙
    static let Wall : UInt32 = 0x1 << 3
    // 分数
    static let Score : UInt32 = 0x1 << 4
}

// 主类
class GameScene: SKScene, SKPhysicsContactDelegate {
    
    var moving:SKNode!
    var teddy:SKSpriteNode!
    var groundTexture = SKTexture(imageNamed: "g1")

    override func didMoveToView(view: SKView) {
        
        // setup physics
        self.physicsWorld.gravity = CGVector( dx: 0.0, dy: -5.0 )
        self.physicsWorld.contactDelegate = self
        
        moving = SKNode()
        self.addChild(moving)

        addGround()
        addBackground()
        addTeddy()
    }
    
    func addGround() {
        
        groundTexture.filteringMode = .Nearest
        let moveGroundSprite = SKAction.moveByX(-groundTexture.size().width * 4.0, y: 0, duration: NSTimeInterval(0.02 * groundTexture.size().width * 2.0))
        let resetGroundSprite = SKAction.moveByX(groundTexture.size().width * 4.0, y: 0, duration: 0.0)
        let moveGroundSpritesForever = SKAction.repeatActionForever(SKAction.sequence([moveGroundSprite,resetGroundSprite]))
        
        for var i:CGFloat = 0; i < 4.0 + self.frame.size.width / ( groundTexture.size().width * 4.0 ); ++i {
            

            let sprite = SKSpriteNode(texture: groundTexture)
            sprite.setScale(4.0)
            sprite.position = CGPoint(x: i * sprite.size.width, y: sprite.size.height / 2.0)
            
            sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
            
            sprite.physicsBody?.dynamic = false
            
            sprite.physicsBody?.affectedByGravity = false
            
            sprite.physicsBody?.categoryBitMask = PhysicsCatagory.Ground
            //sprite.physicsBody?.collisionBitMask = PhysicsCatagory.Teddy
            sprite.physicsBody?.contactTestBitMask  = PhysicsCatagory.Teddy
            sprite.runAction(moveGroundSpritesForever)
            setupGroundAnimation(sprite)
            moving.addChild(sprite)
        }
    }
    
    func addTeddy() {
        let teddyTexture1 = SKTexture(imageNamed: "tt0")
        teddyTexture1.filteringMode = .Nearest
        let teddyTexture2 = SKTexture(imageNamed: "tt1")
        teddyTexture2.filteringMode = .Nearest
        let teddyTexture3 = SKTexture(imageNamed: "tt2")
        teddyTexture3.filteringMode = .Nearest
        
        let teddyTexture4 = SKTexture(imageNamed: "tt3")
        teddyTexture4.filteringMode = .Nearest
        
        let teddyTexture5 = SKTexture(imageNamed: "tt4")
        teddyTexture5.filteringMode = .Nearest
        
        let teddyTexture6 = SKTexture(imageNamed: "tt5")
        teddyTexture6.filteringMode = .Nearest
        
        let anim = SKAction.animateWithTextures([teddyTexture1,teddyTexture2,teddyTexture3,teddyTexture4,teddyTexture5,teddyTexture6], timePerFrame: 0.2)
        let flap = SKAction.repeatActionForever(anim)
        
        teddy = SKSpriteNode(texture: teddyTexture1)
        teddy.setScale(2.0)
        teddy.position = CGPoint(x: self.frame.size.width * 0.45, y:500)
        
        teddy.runAction(flap, withKey: "running")
        
        teddy.physicsBody = SKPhysicsBody(rectangleOfSize: teddy.size)
        teddy.physicsBody?.dynamic = true
        teddy.physicsBody?.allowsRotation = false

        teddy.physicsBody?.categoryBitMask = PhysicsCatagory.Teddy
        //teddy.physicsBody?.collisionBitMask = PhysicsCatagory.Wall
        teddy.physicsBody?.contactTestBitMask = PhysicsCatagory.Ground
        
        self.addChild(teddy)
    }
    
    func addBackground() {
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */
        
        for touch in touches {
            let location = touch.locationInNode(self)
            
            var textures: Array<SKTexture> = []
            
            for i in 1..<4 {
                textures.append(SKTexture(imageNamed: "j\(i)"))
            }
            
            let walkSize = teddy.size
            let jumpSize = textures[0].size().width
            print(walkSize.height)
            print(walkSize.width)
            print(jumpSize)
            
            let playerAnimation = SKAction.animateWithTextures(textures, timePerFrame: 0.5)
            let jump = SKAction.repeatAction(playerAnimation, count: 1)
            
            if (teddy.actionForKey("jumping") == nil)
            {
                
                teddy.runAction(jump, withKey: "jumping")
                teddy.size = CGSize(width: jumpSize * 1.9, height: jumpSize * 1.9)
                teddy.physicsBody = SKPhysicsBody(rectangleOfSize: teddy.size)
                teddy.physicsBody?.velocity = CGVectorMake(0, 0)
                teddy.physicsBody?.applyImpulse(CGVectorMake(0, 40))
               
                teddy.runAction(jump, completion: {
                    self.teddy.size = walkSize
                    self.teddy.physicsBody = SKPhysicsBody(rectangleOfSize: self.teddy.size)
                })
                
            }
            

        }
    }
   
    override func update(currentTime: CFTimeInterval) {
       
    }
    
    func setupGroundAnimation(ground: SKSpriteNode) {
        
        var textures: Array<SKTexture> = []
        
        for i in 1..<4 {
            textures.append(SKTexture(imageNamed: "g\(i)"))
        }
        
        let groundAnimation = SKAction.animateWithTextures(textures, timePerFrame: 0.3333)
        ground.runAction(SKAction.repeatActionForever(groundAnimation))
        
    }
    
    
    func didBeginContact(contact: SKPhysicsContact) {
//        let firstBody = contact.bodyA
//        let secondBody = contact.bodyB
//        
//        if secondBody.categoryBitMask == PhysicsCatagory.Teddy && firstBody.categoryBitMask == PhysicsCatagory.Ground {
//            
//            let teddyTexture1 = SKTexture(imageNamed: "t1")
//            teddyTexture1.filteringMode = .Nearest
//            let teddyTexture2 = SKTexture(imageNamed: "t2")
//            teddyTexture2.filteringMode = .Nearest
//            let teddyTexture3 = SKTexture(imageNamed: "t3")
//            teddyTexture2.filteringMode = .Nearest
//            
//            let anim = SKAction.animateWithTextures([teddyTexture1,teddyTexture2,teddyTexture3], timePerFrame: 0.2)
//            let flap = SKAction.repeatActionForever(anim)
//            
//            teddy = SKSpriteNode(texture: teddyTexture1)
//            teddy.setScale(2.0)
//            teddy.runAction(flap)
//
//        }


    }

}
